package com.heima.search.service.impl;

import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadLocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 保存用户搜索历史记录
     *
     * @param dto
     */
    @Override
    @Async("taskExecutor") // 异步执行线程池
    public void insert(UserSearchDTO dto) {
        //1 参数检查
        String searchWords = dto.getSearchWords();
        Integer loginUserId = dto.getLoginUserId();
        //2 查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(loginUserId, dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry apBehaviorEntry = result.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 查询当前用户搜索的关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(loginUserId).and("keyword").is(searchWords)), ApUserSearch.class);
        //3.1 存在则更新最新时间，更新状态
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.2 不存在则新增
        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setEntryId(apBehaviorEntry.getId());
        apUserSearch.setKeyword(searchWords);
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 查询用户搜索历史记录  显示10条
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        // 1 查询用户得登录信息
        ApUser user = AppThreadLocalUtils.getUser();
        // 2 根据用户id或设备id 查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        // 3 根据行为实体id查询 查询记录
        // 默认查询10条历史记录,并且按照时间降序排序
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                .limit(10)
                , ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }
    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        // 1 校验参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 获取当前用户
        ApUser user = AppThreadLocalUtils.getUser();
        // 3 根据当前用户id和设备id查询行为实体对象
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(!result.checkCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        // 4 调用方法删除mongo里面得数据
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }
}